package JAVA300.第十一章多线程;

/**
 * 取钱线程-添加同步块
 */

public class thread_15_synchronized1_safe2_1 {
    public static void main(String[] args) {

        SynAccounts account = new SynAccounts(500,"hqqs money");
        SynDrawing hqq = new SynDrawing(account,100,"hqq-hpv");
        SynDrawing qyh = new SynDrawing(account,300,"qyh-nike");
        hqq.start();
        qyh.start();


    }

}

class SynAccounts {
     int money;
     String name;

    public SynAccounts(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

class SynDrawing extends Thread{
    SynAccounts account;//取得账户
    int drawingMoney;//单次取得钱数
    int gettotal;//总共取得钱数

    public SynDrawing(SynAccounts account, int drawingMoney,String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        test();

    }
    //目标锁定失败，应该锁的是对象

    public  void test(){

        if (account.money < 0){
            return;
        }

        //同步块---为了进一步提高效率 避免已经咩有钱了但还是要进来等锁，在前面添加判断
        synchronized(account){
            //添加安全控制--防止出现负数-控制不住 引出第三个不安全类
            if ( account.money - drawingMoney <0){
                return;
            }

            //模拟网络延时
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(this.getName()+"-->账户余额为："+account.money);
            gettotal += drawingMoney;
            account.money -= drawingMoney;

            System.out.println(this.getName()+"-->口袋的钱为："+gettotal);
        }


    }
}


